package com.woniuxy.commons.sentinel;

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.woniuxy.movie.commons.core.model.Result;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class BlockHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        Result<?> result = Result.getResult().setMsg("流控").setCode(500);
        if (e instanceof DegradeException){
            result.setMsg("熔断");
        }
        response.setCharacterEncoding("utf8");
        response.setContentType("application/json;charset=utf8");
        String json = JSONUtil.toJsonStr(result);
        response.getWriter().write(json);
        response.getWriter().flush();
    }
}
